package com.castle.fortress.admin.study.exam.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.castle.fortress.admin.core.constants.GlobalConstants;
import com.castle.fortress.admin.study.exam.entity.StudyExamQuestionEntity;
import com.castle.fortress.admin.study.exam.entity.StudyQuestionEntity;
import com.castle.fortress.admin.study.exam.dto.StudyQuestionDto;
import com.castle.fortress.admin.study.exam.service.StudyExamQuestionService;
import com.castle.fortress.admin.study.exam.service.StudyQuestionService;
import com.castle.fortress.common.respcode.BizErrorCode;
import com.castle.fortress.common.utils.ConvertUtil;
import com.castle.fortress.common.entity.RespBody;
import com.castle.fortress.common.exception.BizException;
import com.castle.fortress.common.respcode.GlobalRespCode;
import com.castle.fortress.common.enums.OperationTypeEnum;
import com.castle.fortress.admin.core.annotation.CastleLog;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import springfox.documentation.annotations.ApiIgnore;
import org.apache.logging.log4j.util.Strings;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;
import com.castle.fortress.admin.utils.ExcelUtils;
import javax.servlet.http.HttpServletResponse;
import com.castle.fortress.common.entity.DynamicExcelEntity;
import java.util.List;
import java.util.Map;

/**
 * 题目 控制器
 *
 * @author castle
 * @since 2023-02-10
 */
@Api(tags="题目管理控制器")
@Controller
public class StudyQuestionController {
    @Autowired
    private StudyQuestionService studyQuestionService;
    @Autowired
    private StudyExamQuestionService studyExamQuestionService;

    /**
     * 题目的分页展示
     * @param studyQuestionDto 题目实体类
     * @param current 当前页
     * @param size  每页记录数
     * @return
     */
    @CastleLog(operLocation="题目",operType = OperationTypeEnum.QUERY)
    @ApiOperation("题目分页展示")
    @GetMapping("/study/exam/studyQuestion/page")
    @ResponseBody
    @RequiresPermissions("study:exam:studyQuestion:pageList")
    public RespBody<IPage<StudyQuestionDto>> pageStudyQuestion(StudyQuestionDto studyQuestionDto, @RequestParam(required = false) Integer current, @RequestParam(required = false)Integer size){
        Integer pageIndex= current==null? GlobalConstants.DEFAULT_PAGE_INDEX:current;
        Integer pageSize= size==null? GlobalConstants.DEFAULT_PAGE_SIZE:size;
        Page<StudyQuestionDto> page = new Page(pageIndex, pageSize);
        IPage<StudyQuestionDto> pages = studyQuestionService.pageStudyQuestionExtends(page, studyQuestionDto);

        return RespBody.data(pages);
    }

    /**
     * 题目的列表展示
     * @param studyQuestionDto 题目实体类
     * @return
     */
    @CastleLog(operLocation="题目",operType = OperationTypeEnum.QUERY)
    @ApiOperation("题目列表展示")
    @GetMapping("/study/exam/studyQuestion/list")
    @ResponseBody
    public RespBody<List<StudyQuestionDto>> listStudyQuestion(StudyQuestionDto studyQuestionDto){
        List<StudyQuestionDto> list = studyQuestionService.listStudyQuestion(studyQuestionDto);
        return RespBody.data(list);
    }

    /**
     * 题目保存
     * @param studyQuestionDto 题目实体类
     * @return
     */
    @CastleLog(operLocation="题目",operType = OperationTypeEnum.INSERT)
    @ApiOperation("题目保存")
    @PostMapping("/study/exam/studyQuestion/save")
    @ResponseBody
    @RequiresPermissions("study:exam:studyQuestion:save")
    public RespBody<String> saveStudyQuestion(@RequestBody StudyQuestionDto studyQuestionDto){
        if(studyQuestionDto == null ){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        StudyQuestionEntity studyQuestionEntity = ConvertUtil.transformObj(studyQuestionDto,StudyQuestionEntity.class);
        if(studyQuestionService.checkName(studyQuestionEntity)){
            throw new BizException(BizErrorCode.TITLE_EIXST_ERROR);
        }
        if(studyQuestionService.save(studyQuestionEntity)){
            return RespBody.data("保存成功");
        }else{
            return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
        }
    }

    /**
     * 题目编辑
     * @param studyQuestionDto 题目实体类
     * @return
     */
    @CastleLog(operLocation="题目",operType = OperationTypeEnum.UPDATE)
    @ApiOperation("题目编辑")
    @PostMapping("/study/exam/studyQuestion/edit")
    @ResponseBody
    @RequiresPermissions("study:exam:studyQuestion:edit")
    public RespBody<String> updateStudyQuestion(@RequestBody StudyQuestionDto studyQuestionDto){
        if(studyQuestionDto == null || studyQuestionDto.getId() == null || studyQuestionDto.getId().equals(0L)){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        StudyQuestionEntity studyQuestionEntity = ConvertUtil.transformObj(studyQuestionDto,StudyQuestionEntity.class);
        if(studyQuestionService.checkName(studyQuestionEntity)){
            throw new BizException(BizErrorCode.TITLE_EIXST_ERROR);
        }
        if(studyQuestionService.updateById(studyQuestionEntity)){
            return RespBody.data("保存成功");
        }else{
            return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
        }
    }

    /**
     * 调整题目顺序
     * @param studyQuestionDto 题目实体类
     * @return
     */
    @CastleLog(operLocation="题目",operType = OperationTypeEnum.UPDATE)
    @ApiOperation("调整题目顺序")
    @PostMapping("/study/exam/studyQuestion/editSort")
    @ResponseBody
    @RequiresPermissions("study:exam:studyQuestion:edit")
    public RespBody<String> updateStudyQuestionSort(@RequestBody StudyQuestionDto studyQuestionDto){
        if(studyQuestionDto == null || studyQuestionDto.getId() == null || studyQuestionDto.getId().equals(0L)){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        if(studyQuestionService.updateStudyQuestionSort(studyQuestionDto.getId(),studyQuestionDto.getSort())){
            return RespBody.data("保存成功");
        }else{
            return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
        }
    }

    /**
     * 题目删除
     * @param id
     * @return
     */
    @CastleLog(operLocation="题目",operType = OperationTypeEnum.DELETE)
    @ApiOperation("题目删除")
    @PostMapping("/study/exam/studyQuestion/delete")
    @ResponseBody
    @RequiresPermissions("study:exam:studyQuestion:delete")
    public RespBody<String> deleteStudyQuestion(@RequestParam Long id){
        if(id == null ){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        //校验是否被试卷绑定
        QueryWrapper<StudyExamQuestionEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("question_id",id);
        List<StudyExamQuestionEntity> list = studyExamQuestionService.list(wrapper);
        if(list!=null && list.size()>0){
            throw new BizException(BizErrorCode.QUESTION_BIND_DEL_ERROR);
        }
        if(studyQuestionService.removeById(id)) {
            return RespBody.data("保存成功");
        }else{
            return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
        }
    }


    /**
     * 题目批量删除
     * @param ids
     * @return
     */
    @CastleLog(operLocation="题目",operType = OperationTypeEnum.DELETE)
    @ApiOperation("题目批量删除")
    @PostMapping("/study/exam/studyQuestion/deleteBatch")
    @ResponseBody
    @RequiresPermissions("study:exam:studyQuestion:deleteBatch")
    public RespBody<String> deleteStudyQuestionBatch(@RequestBody List<Long> ids){
        if(ids == null || ids.size()<1){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        //校验是否被试卷绑定
        QueryWrapper<StudyExamQuestionEntity> wrapper = new QueryWrapper<>();
        wrapper.in("question_id",ids);
        List<StudyExamQuestionEntity> list = studyExamQuestionService.list(wrapper);
        if(list!=null && list.size()>0){
            throw new BizException(BizErrorCode.QUESTION_BIND_DEL_ERROR);
        }
        if(studyQuestionService.removeByIds(ids)) {
            return RespBody.data("保存成功");
        }else{
            return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
        }
    }

    /**
     * 题目详情
     * @param id 题目id
     * @return
     */
    @CastleLog(operLocation="题目",operType = OperationTypeEnum.QUERY)
    @ApiOperation("题目详情")
    @GetMapping("/study/exam/studyQuestion/info")
    @ResponseBody
    @RequiresPermissions("study:exam:studyQuestion:info")
    public RespBody<StudyQuestionDto> infoStudyQuestion(@RequestParam Long id){
        if(id == null){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        StudyQuestionDto studyQuestionDto =  studyQuestionService.getByIdExtends(id);

        return RespBody.data(studyQuestionDto);
    }

	/**
     * 动态表头导出 依据展示的字段导出对应报表
     * @param dynamicExcelEntity
     * @param response
     * @throws Exception
     */
    @CastleLog(operLocation="题目",operType = OperationTypeEnum.EXPORT)
	@PostMapping("/study/exam/studyQuestion/exportDynamic")
	@ApiOperation("动态表头导出，依据展示的字段导出对应报表")
	public void exportDynamic(@RequestBody DynamicExcelEntity<StudyQuestionDto> dynamicExcelEntity, HttpServletResponse response) throws Exception {
		List<StudyQuestionDto> list = studyQuestionService.listStudyQuestion(dynamicExcelEntity.getDto());
		//字典、枚举、接口、json常量等转义后的列表数据 根据实际情况初始化该对象，null为list数据直接导出
		List<List<Object>> dataList = null;
		/**
        * 根据实际情况初始化dataList,可参照 com.castle.fortress.admin.system.controller.TmpDemoController类中方法：exportDynamic
        */
		ExcelUtils.exportDynamic(response,dynamicExcelEntity.getFileName()+".xlsx",null,list,dynamicExcelEntity.getHeaderList(),dataList);
	}

    @CastleLog(operLocation="题目",operType = OperationTypeEnum.IMPORT)
    @PostMapping("/study/exam/studyQuestion/importQuestions")
    @ResponseBody
    @ApiOperation("题目导入")
    public RespBody<String> importQuestions(@RequestBody Map<String, Object> params) {
        if(params.get("url")==null || params.get("qbId") == null){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        // 获取文件的地址
        String url = params.get("url").toString();
        Long qbId=Long.parseLong(params.get("qbId").toString());
        return studyQuestionService.importQuestions(url,qbId);
    }


}
